package com.itqf.Controller;

import com.itqf.Enum.CodeEnum;
import com.itqf.Service.User.UserService;

import com.itqf.Util.*;
import com.itqf.Util.DTO.ResultDTO;
import com.itqf.Util.JwtUtile.JwtUtils;
import com.itqf.Util.requestHeader.RequestHeaderUtil;
import com.itqf.entity.User;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(produces = "application/json;charset=utf-8")
public class UserController
{
    @Resource
    private UserService userService;
    /**
     * 我的页面显示
     *
     * */
    @RequestMapping(value = "/huileme/a/u/wode/UserController/FindByid",method = RequestMethod.GET)
    @ResponseBody
    public ResultDTO<User> FindBytoken(HttpServletRequest request)
    {
//        调用获取请求头中的工具类
//        RequestHeaderUtil requestHeaderUtil=new RequestHeaderUtil();
//        final User getheader = requestHeaderUtil.getheader(request);
//        final String userid1 = getheader.getUserid();

        User user = userService.FindFindByuid("1");
        ResultDTO resultDTO=new ResultDTO();
        if (user!=null)
        {
            resultDTO.setData(user);
            resultDTO.setMessage(CodeEnum.selectsuccess.getMsg());
            resultDTO.setCode(CodeEnum.selectsuccess.getCode());
        }else
        {
            resultDTO.setMessage(CodeEnum.selecterror.getMsg());
            resultDTO.setCode(CodeEnum.selecterror.getCode());
        }

         return resultDTO;

    }

/*
开通会员

 */
    @PostMapping("/huileme/a/u/UserController/updetfindbyuserstate")
    @ResponseBody()
    public ResultDTO updetfindbyuserstate(HttpServletRequest request, Integer paystate){
        RequestHeaderUtil requestHeaderUtil=new RequestHeaderUtil();
        final User getheader = requestHeaderUtil.getheader(request);
        final String userid = getheader.getUserid();

       /* User user = userService.findbytoken(token);
        SuccessMessages successMessages = new SuccessMessages();
        String userid = user.getUserid();*/
        ResultDTO resultDTO=new ResultDTO();
        if (!paystate.equals(null)&&paystate.equals(1)){//0支付失败  1支付成功
            int i = userService.updetfindbyuserstate(userid);
            if (i>0){
                resultDTO.setCode(CodeEnum.Updatesuccess.getCode());
                resultDTO.setMessage("开通成功");
            }else
            {
                resultDTO.setCode(CodeEnum.Updateerror.getCode());
                resultDTO.setMessage("开通失败");
            }
        }else
        {
            resultDTO.setCode(CodeEnum.Updateerror.getCode());
            resultDTO.setMessage("支付失败");
        }
        return resultDTO;
    }




    @RequestMapping(value = "/huileme/a/u/UserController/choicegread",method = RequestMethod.GET)
    //@ResponseBody
    /** 
        * @Description:  
        * @Param: [gradeid, response, request] 
        * @return: void 
        * @Author: 赵渊
        * @Date: 19:49 
        *///选择用户年级，选择完成后根据年级跳转到首页
    public void choicegread(int gradeid,HttpServletResponse response,HttpServletRequest request)
    {
         RequestHeaderUtil requestHeaderUtil=new RequestHeaderUtil();
         final User getheader = requestHeaderUtil.getheader(request);
         final String userid = getheader.getUserid();
            response.setContentType("text/html;charset=utf-8");
            try {
                PrintWriter out = response.getWriter();
                userService.updateusergread(userid,gradeid);
                out.print("<script>alert('选择成功');location.href='/homePage?gradeid="+gradeid+"';</script>");
            } catch (IOException e) {
                e.printStackTrace();
            }
    }


    @RequestMapping(value = "/huileme/a/u/UserController/findgrade",method = RequestMethod.GET)
    @ResponseBody
    /** 
        * @Description:  
        * @Param: [response, request] 
        * @return: java.util.List<java.lang.String> 
        * @Author: 赵渊
        * @Date: 19:53
        *///查找这个用户存在的年级
    public ResultDTO<Map> findgrade(HttpServletResponse response,HttpServletRequest request)
    {
        RequestHeaderUtil requestHeaderUtil=new RequestHeaderUtil();
        final User getheader = requestHeaderUtil.getheader(request);
        final String userid = getheader.getUserid();
        //response.setContentType("text/html;charset=utf-8");
        String grade = userService.finduserandgrade(userid);
        Map map=new HashMap();
        map.put("grade",grade);
        ResultDTO resultDTO=new ResultDTO();

        resultDTO.setMessage(CodeEnum.selectsuccess.getMsg());
        resultDTO.setCode(CodeEnum.selectsuccess.getCode());
        resultDTO.setData(map);
        return resultDTO;
    }


     /*
    杨帅
     */

    /**
     * 邮箱找回密码
     * @param email
     * @return
     */
    @RequestMapping(value = "/huileme/a/m/UserController/emailFind",method = RequestMethod.GET)
    @ResponseBody
    @ApiImplicitParams({@ApiImplicitParam
            (value = "邮箱账号" ,name = "email",dataType = "string",required =true )})
    public ResultDTO<String> findPassWordByEmail(String email){
        System.out.println(email);
        String string = userService.getUserByUserName(email);
        ResultDTO resultDTO=new ResultDTO();
        resultDTO.setMessage(string);
        resultDTO.setCode(CodeEnum.selecterror.getCode());
        return resultDTO;
    }

    /**
     * 邮箱 密码 登录
     * @param email
     * @param userPassWord
     * @param session
     * @param response
     * @return
     */
    @RequestMapping(value = "/huileme/a/m/UserController/emailLogin",method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO<String> loginByEmailAndPassWord(String email, String userPassWord,HttpSession session, HttpServletResponse response){
        ResultDTO<String> message = new ResultDTO<>();
        User user = userService.getUserByUser(email, userPassWord);
        if (user==null){
            message.setMessage("邮箱尚未注册");
            message.setCode(CodeEnum.selecterror.getCode());
            return message;
        }
        try {
            userPassWord = Md5Util.encodeByMd5(userPassWord);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!userPassWord.equals(user.getUserpassword())) {
            message.setMessage("邮箱或密码不正确");
            message.setCode(CodeEnum.selecterror.getCode());
            return message;
        }
        String token = JwtUtils.geneJsonWebTokenByEmail(user);
        user.setUserToken(token);
        userService.updateUserByToken(user);
       /* Cookie cookie=new Cookie("token",token);

        cookie.setMaxAge( 1000 * 60 * 60 * 24 * 12);
        //将Cookie放到响应中返回
        response.addCookie(cookie);*/
        response.addHeader("x-access-token",token);

        message.setMessage("登录成功");
        message.setCode(CodeEnum.addsuccess.getCode());
        return message;
    }

    /**
     * 得到邮箱验证码
     * @param session
     * @param userName
     */
    @RequestMapping(value = "/huileme/a/m/UserController/getCode",method = RequestMethod.GET)
    @ResponseBody
    public void getFourNumber(HttpSession session, String userName){
        String number = RandomStringTLUtils.randomNumeric(4);
        session.setAttribute("number",number);
        session.setMaxInactiveInterval(5000);
        MailUtils.sendMail(userName,"验证码是:"+number,"验证码");
        //return number;
    }

    /**
     * 邮箱注册账号
     * @param email
     * @param userPassWord
     * @param verificationCode
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/huileme/a/m/UserController/emailRegister",method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO<String> insert(String email,String userPassWord,String verificationCode,HttpSession session) throws Exception {
        ResultDTO<String> message = new ResultDTO<>();
        if (!verificationCode.equals(session.getAttribute("number"))) {
            message.setMessage("验证码不正确");
            message.setCode(CodeEnum.parameterincomplete.getCode());
            return message;
        }
        if(userService.getUserByUser(email, userPassWord)!=null){
            message.setMessage("邮箱已注册");
            message.setCode(CodeEnum.parameterincomplete.getCode());
            return message;
        }
        User insertUser = new User();
        insertUser.setUserid(UuidUtil.getUuid());
        insertUser.setEmail(email);
        insertUser.setUserpassword(Md5Util.encodeByMd5(userPassWord));
        String string = userService.insert(insertUser);
        message.setMessage(string);
        message.setCode(CodeEnum.addsuccess.getCode());
        return message;
    }

    /**
     * 邮箱修改密码
     * @param email
     * @param userPassWord
     * @param verificationCode
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/huileme/a/m/UserController/emailUpdate",method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO<String> updatePassWordByEmail(String email,String userPassWord,String verificationCode,HttpSession session) throws Exception {
        ResultDTO<String> message = new ResultDTO<>();
        if (!verificationCode.equals(session.getAttribute("number"))) {
            message.setMessage("验证码不正确");
            message.setCode(CodeEnum.parameterincomplete.getCode());
            return message;
        }
        if(userService.getUserByUser(email,userPassWord)==null){
            message.setMessage("邮箱不正确");
            message.setCode(CodeEnum.parameterincomplete.getCode());
            return message;
        }
        User user = new User();
        user.setEmail(email);
        user.setUserpassword(Md5Util.encodeByMd5(userPassWord));
        String s = userService.updatePassWordByEmail(user);
        message.setMessage(s);
        message.setCode(CodeEnum.Updatesuccess.getCode());
        return message;
    }

    /**
     * 得到手机验证码
     * @param request
     * @param phoneNum
     * @return
     */
    @RequestMapping(value = "/huileme/a/m/UserController/loginpasswordto",method = RequestMethod.GET)
    public String getPhoneNumber(HttpServletRequest request, String phoneNum){
        String numeric = RandomStringTLUtils.randomNumeric(4);
        request.getSession().setAttribute("sjyzm",numeric);
        return "redirect:/loginpassword1?phoneNum="+phoneNum+"&numeric="+numeric;
    }

    /**
     * 手机验证码登录
     * @param response
     * @param phoneNumber
     * @param verificationCode
     * @param session
     * @return
     */
    @PostMapping("/huileme/a/m/UserController/phoneLogin")
    @ResponseBody
    public ResultDTO<String> phoneLogin(HttpServletResponse response,String phoneNumber,String verificationCode,HttpSession session){

        ResultDTO<String> message = new ResultDTO<>();
        //System.out.println(session.getAttribute("sjyzm")+"===========================");
        if (!verificationCode.equals(session.getAttribute("sjyzm"))){
            message.setMessage("验证码错误");
            message.setCode(CodeEnum.parameterincomplete.getCode());
            return message;
        }
       /* Claims token = JwtUtils.checkToken(userToken);
        String phone = (String) token.get("name");*/
        User user = userService.getUserByPhone(phoneNumber);
        if (user==null) {
            user = new User();
            user.setUserid(UuidUtil.getUuid());
            user.setUserPhone(phoneNumber);
            userService.insertUserByPhone(user);
        }
        String token = JwtUtils.geneJsonWebTokenByPhone(user);
        user.setUserToken(token);
        userService.updateUserByToken(user);
        /*Cookie cookie=new Cookie("token",token);
        cookie.setMaxAge( 1000 * 60 * 60 * 24 * 12);

        //将Cookie放到响应中返回
        response.addCookie(cookie);*/
        response.addHeader("x-access-token",token);

        message.setMessage("登录成功");
        message.setCode(CodeEnum.parameterincomplete.getCode());
        return message;
    }

    /**
     * 手机号 密码 登录
     * @param response
     * @param phoneNumber
     * @param userPassWord
     * @return
     */
    @PostMapping("/huileme/a/m/UserController/phoneLoginByPass")
    @ResponseBody
    public ResultDTO<String> phoneLoginByPass(HttpServletResponse response,String phoneNumber,String userPassWord){
        ResultDTO<String> message = new ResultDTO<>();
        User user = userService.getUserByPhone(phoneNumber);
        try {
            userPassWord = Md5Util.encodeByMd5(userPassWord);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (user==null || !userPassWord.equals(user.getPhonepassword())){
            message.setMessage("手机号或者密码错误");
            message.setCode(CodeEnum.parameterincomplete.getCode());
            return message;
        }
        String token = JwtUtils.geneJsonWebTokenByPhone(user);
        user.setUserToken(token);
        userService.updateUserByToken(user);
       /* Cookie cookie=new Cookie("token",token);
        cookie.setMaxAge( 1000 * 60 * 60 * 24 * 12);

        //将Cookie放到响应中返回
        response.addCookie(cookie);*/
       response.addHeader("x-access-token",token);

        message.setMessage("登录成功");
        message.setCode(CodeEnum.addsuccess.getCode());
        return message;
    }

    /**
     * 手机修改密码
     * @param session
     * @param phoneNumber
     * @param userPassWord
     * @param verificationCode
     * @return
     */
    @PostMapping("/huileme/a/m/UserController/phoneUpdatePassword")
    @ResponseBody
    public ResultDTO<String> phoneUpdatePassword(HttpSession session,String phoneNumber,String userPassWord,String verificationCode){
        ResultDTO<String> messages = new ResultDTO<>();
        if(!verificationCode.equals(session.getAttribute("sjyzm"))){
            messages.setMessage("验证码错误");
            messages.setCode(CodeEnum.parameterincomplete.getCode());
            return messages;
        }
        if(userService.getUserByPhone(phoneNumber)==null){
            messages.setMessage("手机号尚未注册");
            messages.setCode(CodeEnum.parameterincomplete.getCode());
            return messages;
        }
        User user = new User();
        user.setUserPhone(phoneNumber);
        try {
            user.setPhonepassword(Md5Util.encodeByMd5(userPassWord));
        } catch (Exception e) {
            e.printStackTrace();
        }
        int i = userService.phoneUpdatePassword(user);
        messages.setMessage("修改成功");
        messages.setCode(CodeEnum.Updatesuccess.getCode());
        return messages;
    }

    /**
     * 设置手机登录密码
     * @param phoneNumber
     * @param phonepassword
     * @param verificationCode
     * @param session
     * @return
     */
    @PostMapping("/huileme/a/m/UserController/phoneRegister")
    @ResponseBody
    public ResultDTO<String> phoneRegister(String phoneNumber,String phonepassword,String verificationCode,HttpSession session){
        ResultDTO<String> messages = new ResultDTO<>();
        if (!verificationCode.equals(session.getAttribute("sjyzm"))){
            messages.setMessage("验证码错误");
            messages.setCode(CodeEnum.parameterincomplete.getCode());
            return messages;
        }
        User user = new User();
        user.setUserPhone(phoneNumber);
        try {
            user.setPhonepassword(Md5Util.encodeByMd5(phonepassword));
        } catch (Exception e) {
            e.printStackTrace();
        }
        userService.phoneUpdatePassword(user);
        messages.setMessage("设置成功");
        messages.setCode(CodeEnum.parameterincomplete.getCode());
        return messages;
    }
    //jmhh===========



}

